﻿using BootstrapBlazor.Components;
using Common.Api.Client;
using CyssBlazor.Shared.Infrastructure;
using Order.Api.Client;
using Order.Api.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Pages.Orders.SaleOrder
{
    public partial class List
    {
        public SaleOrderSearchModel searchModel { set; get; } = new SaleOrderSearchModel();

        public List()
        {
            this.PageCode = "SaleOrder";
        }

        /// <summary>
        ///数据查询方法
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        protected async Task<QueryData<SaleOrderModel>> OnQueryAsync(QueryPageOptions options)
        {
            //TODO: 此处代码后期精简
            searchModel.pageIndex = options.PageIndex;
            searchModel.pageSize = options.PageItems;
            searchModel.SearchName = options.SearchText;
            var apiResponse = await OrderClientFactory.SaleOrder.GetPageListSaleOrders(searchModel);
            if (apiResponse.IsSuccess && apiResponse.Data != null)
            {
                return await Task.FromResult(new QueryData<SaleOrderModel>()
                {
                    Items = apiResponse.Data.Data,
                    TotalCount = apiResponse.Data.Total
                });
            }
            else
            {
                await this.Toast("获取订单失败:" + apiResponse.Message);
            }
            return null;
        }


        private async Task OpenEdit(SaleOrderModel item)
        {
            this.ShowModal<CreateOrUpdate, SaleOrderModel>($"编辑订单-{item.Number}", item, 1200);
            await Task.CompletedTask;
        }

        protected async Task<bool> OnSaveAsync(SaleOrderModel options, ItemChangedType itemChangedType)
        {
            if (options.Id == 0)
            {
                var operateResult = await CommonClientFactory.Helper.GetIdempotence();
                if (operateResult.IsSuccess)
                {
                    var apiResponse = await OrderClientFactory.SaleOrder.CreateSaleOrder(options, operateResult.Data);
                    return apiResponse.IsSuccess;
                }
                return false;
            }
            else
            {
                var apiResponse = await OrderClientFactory.SaleOrder.EditSaleOrder(options);
                return apiResponse.IsSuccess;
            }
        }

        protected async Task<bool> OnDeleteAsync(IEnumerable<SaleOrderModel> options)
        {
            var apiResponse = await OrderClientFactory.SaleOrder.DeleteSaleOrder(options.FirstOrDefault().Id);
            return apiResponse.IsSuccess;
        }

    }
}
